package com.jvm123.blog.client;

import feign.Client;
import feign.Request;
import feign.Response;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.HashMap;

/**
 * @author yawn http://jvm123.com
 * 2019/12/3 9:52
 */
public class HttpFeignClient implements Client {

    @Override
    public Response execute(Request request, Request.Options options) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpRequestBase httpRequest = new HttpRequestBase() {
            @Override
            public String getMethod() {
                return request.method();
            }
        };
        try {
            httpRequest.setURI(new URI(request.url()));
        } catch (URISyntaxException ignored) { }
        CloseableHttpResponse httpResponse = httpClient.execute(httpRequest);
        HttpEntity entity = httpResponse.getEntity();
        byte[] body = EntityUtils.toByteArray(entity);
        Response response = Response.builder()
                .body(body)
                .headers(new HashMap<String, Collection<String>>())
                .status(httpResponse.getStatusLine().getStatusCode())
                .build();
        return response;
    }
}
